package conchmusic.conchmusicclient.view;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.activity.DownloadActivity;
import conchmusic.conchmusicclient.activity.DownloadSearchActivity;
import conchmusic.conchmusicclient.activity.LocalMusicActivity;
import conchmusic.conchmusicclient.activity.OnlineSearchActivity;
import conchmusic.conchmusicclient.activity.SearchActivity;
import conchmusic.conchmusicclient.mainUi.MainActivity;
import conchmusic.conchmusicclient.util.HistoryResolve;

/**
 * Created by Administrator on 2017/4/10.
 */

public class SearchView extends LinearLayout implements View.OnClickListener {
    private EditText etInput;
    private ImageView ivDelete;
    private Button btnBack;
    private Context mContext;
    private ListView lvTips;
    private ArrayAdapter<String> mHintAdapter;
    private ArrayAdapter<String> mAutoCompleteAdapter;
    private SearchViewListener mListener;
    private ImageView imageButton;
    private HistoryResolve historyResolve;
    private String itermString;
    private View view;
    private int textLength=0;
    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.search_local_music, this);
        initViews();
    }

    public void setSearchViewListener(SearchViewListener listener) {
        mListener = listener;
    }
    private void initViews() {
        etInput = (EditText) findViewById(R.id.search_et_input);
        ivDelete = (ImageView) findViewById(R.id.search_iv_delete);
        btnBack = (Button) findViewById(R.id.search_btn_back);
        lvTips = (ListView) findViewById(R.id.search_lv_tips);
        imageButton=(ImageView)findViewById(R.id.search_image_button);
        lvTips.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                itermString=lvTips.getAdapter().getItem(position).toString();
                Adapter adapter=lvTips.getAdapter();
                String text;
                if(adapter.equals(mHintAdapter)){
                    String[] spliteHintData=itermString.split(":");
                    if(spliteHintData.length>1){
                        text=spliteHintData[1];
                    }else{
                        text="";
                    }
                }else{
                    text=itermString;
                }
                etInput.setText(text);
                etInput.setSelection(text.length());
                lvTips.setVisibility(View.GONE);
                ivDelete.setVisibility(View.VISIBLE);
                notifyStartSearching(text,"ItemOnclick");
            }
        });
        imageButton.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        etInput.setOnClickListener(this);
        etInput.addTextChangedListener(new EditChangedListener());
        etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    lvTips.setVisibility(GONE);
                }
                return true;
            }
        });
    }
    private  void notifyStartSearching(String text,String flag){
        historyResolve=new HistoryResolve(mContext);
        if (mListener != null) {
            Log.i("activity",mContext.getClass().getName());
            if(mContext.getClass().equals(SearchActivity.class)){
                historyResolve.saveHistory(text,flag);
            }else if(mContext.getClass().equals(OnlineSearchActivity.class)){
                if("ItemOnclick".equals(flag)){
                    text=text.split("\\+")[0];
                    Log.i("Search112",text);
                }
                historyResolve.saveOnlineHistory(text,flag);
            }else if(mContext.getClass().equals(DownloadSearchActivity.class)){
                historyResolve.saveDownloadHistory(text,flag);
            }
            mListener.onSearch(etInput.getText().toString(),flag);
        }
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
    public void setTipsHintAdapter(ArrayAdapter<String> adapter) {
        this.mHintAdapter = adapter;
        if (lvTips.getAdapter() == null) {
            lvTips.setAdapter(mHintAdapter);
        }
    }
    public void setHistoryView(View view){
        this.view=view;
    }
    public void setAutoCompleteAdapter(ArrayAdapter<String> adapter) {
        this.mAutoCompleteAdapter = adapter;
    }
    private class EditChangedListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mListener.clearResult();
            Log.i("Search145",s.toString());
            Matcher matcher= Pattern.compile("\\s+").matcher(s);
            if(!matcher.find()){
                ivDelete.setVisibility(VISIBLE);
                lvTips.setVisibility(VISIBLE);
                if (mAutoCompleteAdapter != null && lvTips.getAdapter() != mAutoCompleteAdapter) {
                    lvTips.setAdapter(mAutoCompleteAdapter);
                }
                //更新autoComplete数据
                if (mListener != null) {
                    mListener.onRefreshAutoComplete(s + "");
                }
                if("".equals(s)){
                    ivDelete.setVisibility(GONE);
                }
            }else{
                ivDelete.setVisibility(GONE);
                if (mHintAdapter != null) {
                    lvTips.setAdapter(mHintAdapter);
                }
                lvTips.setVisibility(GONE);
            }
            }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_et_input:
                if(mListener!=null){
                    mListener.clearResult();
                }
                //etInput.setText("");
                lvTips.setVisibility(VISIBLE);
                view.setVisibility(View.GONE);
                break;
            case R.id.search_iv_delete:
                etInput.setText("");
                ivDelete.setVisibility(GONE);
                lvTips.setVisibility(GONE);
                break;
            case R.id.search_btn_back:
                Log.i("className",mContext.getClass().toString());
                if(mContext.getClass().equals(SearchActivity.class)){
                    Intent backLocal=new Intent(mContext,LocalMusicActivity.class);
                    mContext.startActivity(backLocal);
                }else if(mContext.getClass().equals(OnlineSearchActivity.class)){
                    mListener.closeActivity();
                    Intent backOnline=new Intent(mContext, MainActivity.class);
                    mContext.startActivity(backOnline);
                }else if(mContext.getClass().equals(DownloadSearchActivity.class)){
                    Intent intent=new Intent(mContext,DownloadActivity.class);
                    mContext.startActivity(intent);
                }
                break;
            case R.id.search_image_button:
                lvTips.setVisibility(View.GONE);
                String macherString=etInput.getText().toString();
                Matcher matcher= Pattern.compile("\\s+").matcher(macherString);
                if(!matcher.find()&&!macherString.equals(null)){
                    notifyStartSearching(macherString,"SearchAction");
                }
                break;
        }
    }
    public void frushLvTips(Adapter m){
        if (mAutoCompleteAdapter != null) {
            lvTips.setAdapter(mAutoCompleteAdapter);
        }
    }

    /**
     * Created by Administrator on 2017/4/10.
     */

    public static interface SearchViewListener {
        public  void onSearch(String text, String flag);
        public  void onRefreshAutoComplete(String text);
        public void clearResult();
        public void closeActivity();
    }
    public void lvTipslayout(){
        lvTips.requestLayout();
    }
    public String getEtInput(){
        return etInput.getText().toString();
    }
}
